<template>
  <!-- 加载器 -->
  <Loading v-if="isLoading"></Loading>

  <Form
    class="w-1/3 m-auto mt-40 shadow-2xl shadow-red-300 rounded-box"
    v-if="!isLoading"
    :validation-schema="schema"
    @submit="onSubmit"
  >
    <!-- avatar -->
    <div class="avatar flex justify-center">
      <div class="w-24 rounded-full mt-4">
        <label for="avatar-input" class="cursor-pointer">
          <img :src="currentAvatar" />
        </label>
      </div>
    </div>
    <input
      id="avatar-input"
      type="file"
      accept="image/*"
      @change="handleAvatarChange"
      class="hidden"
    />

    <!-- name -->
    <!-- <h1 class="text-4xl text-center pt-4">{{ name }}</h1> -->
    <!-- 班级 -->
    <!-- <label class="input flex gap-2 my-4 w-3/4 mx-auto"
      >Class
      <input
        type="text"
        class="input input-neutra"
        value="Class 1 | Year 8"
        disabled
      />
    </label> -->
    <!-- 分数 -->
    <label class="input flex gap-2 my-4 w-3/4 mx-auto"
      >Name
      <Field
        name="name"
        type="text"
        class="input input-primary"
        v-model="name"
      />
      <ErrorMessage name="name" class="text-red-500" />
    </label>
    <!-- 学科 -->

    <div class="flex gap-2 my-4 w-3/4 mx-auto">
      <select class="select w-full" v-model="gender">
        <label class="label">Gender</label>
        <option disabled selected>Choose Gender</option>
        <option>male</option>
        <option>female</option>
      </select>
    </div>

    <!-- 按钮 -->
    <div class="text-center">
      <button class="btn btn-primary mb-4">Update Profile</button>
    </div>
  </Form>
</template>
<script setup>
import { getToken } from "@/ultils/tokenHelper";
import { useRouter } from "vue-router";
import { uploadAvatar } from "@/services/apiStorage";
import { getStuentById, updateStudent } from "@/services/ApiStudent";
import { getConfig } from "@/ultils/configHelper";
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useToast } from "vue-toastification";
import Loading from "@/ui/Loading.vue";

import { Form, Field, ErrorMessage } from "vee-validate";
import * as yup from "yup";

const schema = yup.object({
  name: yup.string().min(2).required("Name is required"),
});

const isLoading = ref(true);

const toast = useToast();

const name = ref("name");
const gender = ref("male");

//用router.params获取id
const route = useRoute();
const router = useRouter();
const studentId = route.params.id;
// 头像上传
const currentAvatar = ref(
  "https://img.daisyui.com/images/profile/demo/yellingcat@192.webp"
);
const newAvatar = ref(null);

//钩子
onMounted(async () => {
  isLoading.value = true;
  const student = await getStuentById("student_id", studentId);
  console.log(student);
  name.value = student[0].name;
  gender.value = student[0].gender;
  currentAvatar.value = student[0].avatar;
  isLoading.value = false;
});

function handleAvatarChange(e) {
  const file = e.target.files[0];
  newAvatar.value = file;
  const avatarURL = URL.createObjectURL(file);
  currentAvatar.value = avatarURL;
}

async function onSubmit() {
  const supabaseURL = getConfig("SUPABASE_URL");

  const newStudent = {
    name: name.value,
    gender: gender.value,
  };

  if (newAvatar.value) {
    const userToken = getToken();
    const newAvatarFilename = `${userToken.user.email}-${Date.now()}.png`;

    await uploadAvatar(newAvatar.value, newAvatarFilename);

    const avatar = `${supabaseURL}/storage/v1/object/public/avatar/public/${newAvatarFilename}`;

    newStudent.avatar = avatar;
  }
  const student = updateStudent(studentId, newStudent);

  router.push({ name: "student" });
  toast.success("Successfully updated");
}
</script>
